package com.hyy.blogtest.common.advice;


import com.hyy.blogtest.common.exception.BlogException;
import com.hyy.blogtest.common.exception.UserException;
import com.hyy.blogtest.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import javax.imageio.event.IIOReadUpdateListener;

@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {

    //所有异常都会被这里处理，如果具体异常没有捕获
    @ExceptionHandler(value = Exception.class)
    public Result hander(Exception e) {
            log.error("发现其他类型异常：{}",e.getMessage(), e);
            return Result.fail("发现其他类型异常：",e.getMessage());
    }

    //博客异常
    @ExceptionHandler(value= BlogException.class)
    public Result handler(BlogException e) {
        log.error("博客异常：{}",e.getMessage(), e);
        return Result.fail("博客异常：",e.getMessage());

    }


    //没有找到资源
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(value= NoResourceFoundException.class)
    public Result hander(NoResourceFoundException e) {
        log.error("没有找到资源：{}",e.getResourcePath(), e);
        return Result.fail("没有找到资源：",e.getResourcePath());
    }

    //参数不合法 MethodArgumentNotValidException也就是校验参数异常，会被虾米那这个捕获
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value= HandlerMethodValidationException.class)
    public Result handler(HandlerMethodValidationException e) {
        log.error("前端传递参数不合法：{}",e.getMessage(), e);
        return Result.fail("前端传递参数不合法：",e.getMessage());
    }

    //参数不合法 MethodArgumentNotValidException也就是校验参数异常，会被虾米那这个捕获
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value= UserException.class)
    public Result handler(UserException e) {
        log.error("用户类问题出错：{}",e.getMessage(), e);
        return Result.fail("用户类问题出错：",e.getMessage());
    }



}
